#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <mutex>
#include <fstream>
#include <unordered_map>
#include "util.hpp"

namespace ns_index
{
    struct DocInfo
    {
        std::string title;   // 文档标题
        std::string content; // 文档内容
        std::string url;     // 文档在官网的url
        int doc_id;          // 文档的ID
    };

    struct InvertedElem
    {
        uint64_t doc_id;
        std::string word;
        int weight; // 权值（表示相关性）
    };

    // 倒排拉链
    typedef std::vector<InvertedElem> InvertedList;

    class Index
    {
    public:
        ~Index() {}

        static Index *GetInstance()
        {
            if (instance == nullptr)
            {
                mtx.lock();
                if (instance == nullptr)
                {
                    instance = new Index();
                }
            }
            mtx.unlock();
            return instance;
        }

        // 根据doc_id找文档内容
        DocInfo *GetForWardIndex(uint64_t doc_id)
        {
            if (doc_id >= forward_index.size())
            {
                std::cerr << "doc_id out rang! error" << std::endl;
                return nullptr;
            }
            return &forward_index[doc_id];
        }

        // 根据关键字, 获取倒排拉链
        InvertedList *GetInvertedList(const std::string &word)
        {
            auto iter = inverted_index.find(word);
            if (iter == inverted_index.end())
            {
                std::cerr << word << " have no InvertedList" << std::endl;
                return nullptr;
            }

            return &(iter->second);
        }

        // 根据去标签之后的文档构建正排/倒排索引
        bool BuildIndex(const std::string &input)
        {
            std::ifstream in(input, std::ios::in | std::ios::binary);
            if (!in.is_open())
            {
                std::cerr << input << " open error!" << std::endl;
                return false;
            }

            std::string line;

            int count = 0;

            while (std::getline(in, line))
            {
                DocInfo *doc = BulidForwardIndex(line);
                if (doc == nullptr)
                {
                    std::cerr << "Build " << line << " error" << std::endl;
                    continue;
                }

                BulidInvertedIndex(*doc);
                count++;
                if (count % 50 == 0)
                {
                    std::cout << "当前已经建立文档数: " << count << std::endl;
                }
            }
            return true;
        }

    private:
        DocInfo *BulidForwardIndex(const std::string &line)
        {
            // 1. 解析line, 进行字符串切分
            const std::string sep = "\3";
            std::vector<std::string> results;
            ns_util::StringUtill::Split(line, &results, sep);
            if (results.size() != 3)
            {
                return nullptr;
            }
            // 2. 字符串填充到 DocInfo
            DocInfo doc;
            doc.title = results[0];
            doc.content = results[1];
            doc.url = results[2];
            doc.doc_id = forward_index.size();
            // 3. 插入vector
            forward_index.push_back(std::move(doc));
            return &forward_index.back();
        }

        bool BulidInvertedIndex(const DocInfo &doc)
        {
            struct word_cnt
            {
                int title_cnt;
                int content_cnt;

                word_cnt() : title_cnt(0), content_cnt(0) {}
            }; // 统计词频

            std::unordered_map<std::string, word_cnt> word_map; // 用来暂存词频的映射表

            // 对title分词词统计
            std::vector<std::string> title_words; // 统计title切分出来的词
            ns_util::JiebaUtill::CutString(doc.title, &title_words);
            for (auto &s : title_words)
            {
                boost::to_lower(s);
                word_map[s].title_cnt++;
            }

            // 对content做分词统计
            std::vector<std::string> content_words;
            ns_util::JiebaUtill::CutString(doc.content, &content_words);
            for (auto &s : content_words)
            {
                boost::to_lower(s);
                word_map[s].content_cnt++;
            }

#define X 10
#define Y 1
            for (auto &word_pair : word_map)
            {
                InvertedElem item;
                item.doc_id = doc.doc_id;
                item.word = word_pair.first;
                item.weight = X * word_pair.second.title_cnt + Y * word_pair.second.content_cnt;
                InvertedList &inverted_list = inverted_index[word_pair.first];
                inverted_list.push_back(std::move(item));
            }

            return true;
        }

    private:
        Index() {}
        Index(const Index &) = delete;
        Index &operator=(const Index &) = delete;

        static Index *instance;
        static std::mutex mtx;

        // 正排索引数据结构直接可以用数组, 因为数组下标天然就可以是文档的ID
        std::vector<DocInfo> forward_index; // 正排索引

        // 倒排索引一定一个关键字和一组 InvertedElem 对应 (关键字和倒排拉链的映射关系)
        std::unordered_map<std::string, InvertedList> inverted_index; // 倒排索引
    };

    Index *Index::instance = nullptr;
    std::mutex Index::mtx;
};